local base = piece "base"
local turret = piece "turret"
local leftarm = piece "leftarm"
local leftbackhammers = piece "leftbackhammers"
local leftcanons = piece "leftcanons"
local leftbarrels = piece "leftbarrels"
local rightarm = piece "rightarm"
local rightbackhammers = piece "rightbackhammers"
local rightcanons = piece "rightcanons"
local rightbarrels = piece "rightbarrels"
local leftout = piece "leftout"
local rightout = piece "rightout"
local flare = piece "flare"

local SIG_AIM = 1

local function opencanons(piece1, piece2, piece3, piece4)
	Move(piece4, z_axis, -6.5, 50)
        Move(piece1, z_axis, 7.5, 50)
	WaitForMove(piece1, z_axis)
        Move(piece2, z_axis, 10, 50)
	WaitForMove(piece2, z_axis)
        Move(piece3, z_axis, 2, 50)
end

local function closecanons(piece1, piece2, piece3, piece4)
        Move(piece4, z_axis, 0, 50)
        Move(piece1, z_axis, 0, 50)
        WaitForMove(piece1, z_axis) 
        Move(piece2, z_axis, 0, 50)
        WaitForMove(piece2, z_axis) 
        Move(piece3, z_axis, 0, 50)   
end

local function Open()
        Signal(2)
        SetSignalMask(1)

        Move(turret, y_axis, 12, 100)

	Sleep(100)

        Turn(rightarm, z_axis, -0.5, 5)
        Turn(leftarm, z_axis, 0.5, 5)
        Move(rightarm, x_axis, -3, 20) 
        Move(leftarm, x_axis, 3, 20) 

	WaitForMove(leftarm, x_axis)  
	WaitForMove(rightarm, x_axis)  

	StartThread(opencanons, leftcanons, leftbarrels, leftout, leftbackhammers)
	StartThread(opencanons, rightcanons, rightbarrels, rightout, rightbackhammers)

        return true
end

local function Close()
        Signal(1)
        SetSignalMask(2)
	
        Turn(rightarm, z_axis, 0, 5)
        Turn(leftarm, z_axis, 0, 5)
        Move(rightarm, x_axis, 0, 20)
        Move(leftarm, x_axis, 0, 20)  

        WaitForMove(rightarm, x_axis)
	WaitForMove(leftarm, x_axis)  

        StartThread(closecanons, leftcanons, leftbarrels, leftout, leftbackhammers)
        StartThread(closecanons, rightcanons, rightbarrels, rightout, rightbackhammers)

	Sleep(100)
	Move(turret, y_axis, 0, 50)
        return true
end

function script.Create()
	Hide(flare)
end

function script.AimWeapon1(heading, pitch)
	Signal(SIG_AIM)
	SetSignalMask(SIG_AIM)
	Turn(turret, y_axis, heading, 0.5)
	Turn(leftarm, x_axis, -pitch, 0.25)
	Turn(rightarm, x_axis, -pitch, 0.25)
	WaitForTurn(turret, y_axis)
	WaitForTurn(leftarm, x_axis)
	WaitForTurn(rightarm, x_axis)
	return true
end

function script.QueryWeapon1() return turret end

function script.AimFromWeapon1() return turret end

function script.FireWeapon1()
	Show(flare)
	Move(leftbarrels, z_axis, -2.4)
	Move(rightbarrels, z_axis, -2.4)
	Sleep(150)
	Hide(flare)
	Move(leftbarrels, z_axis, 0, 3)
	Move(rightbarrels, z_axis, 0, 3)
end

function script.Activate ( )
        StartThread( Open )
end

function script.Deactivate ( )
        StartThread( Close )
end
